const usersModels=require('../models/users')
const tools=require('../utils/tools')
const authMiddle=require('../middleware/auth')

const signup=async function(req, res, next) {
 // console.log(req.body)
 res.set('Content-Type', 'application/json; charset=utf-8')
 let {username,password}=req.body
//console.log(username,password,0)
  let hash=await tools.hash(password)
 // console.log(hash)
  let result=await usersModels.save({
    username,
    password:hash
  }) 
 // console.log(result)
  if(result){
    res.render("success",{
     data: JSON.stringify({
      message:'用户注册成功'
    })
})
}else{
    res.render("fail",{
        data: JSON.stringify({
         message:'用户注册失败'
       })
   })
}
}

const signin=async  function(req,res,next){
 res.set('Content-Type', 'application/json; charset=utf-8')

  let {username,password}=req.body

  let result=await usersModels.findOne({username})

  if(result){
    let cpass=await tools.compare(password,result.password)
    if(cpass){
   //   console.log(username);
    let token=await tools.generateToken(username) 
      res.header('X-Access-Token',token)
     
    res.render("success",{
      data: JSON.stringify({
        username:username,
        issign:true,
       message:'登录成功'
     })
  })
}
else{
  res.render("fail",{
    data: JSON.stringify({
     message:'用户名或密码错误'
   })
})
}
  }else{
    res.render("fail",{
      data: JSON.stringify({
       message:'用户名或密码错误'
     })
  })
  }

}


const isSignin=authMiddle


const signout=function(req,res,next){
  req.session=null
  res.render("success",{
    data: JSON.stringify({
      message:'注销成功'
   })
})
}

const hasusername=async function(req,res,next){
 res.set('Content-Type', 'application/json; charset=utf-8')
  let {username}=req.body
 let result= await usersModels.findOne({username})
 if(result){
  res.render("fail",{
    data: JSON.stringify({
     message:'用户名已经存在'
   })
})
 }else{
   next()
 }
}


module.exports={
    signup,
    hasusername,
    signin,
    signout,
    isSignin
}

